<template>
  <div class="app-container bg">
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 160px" prop="registerTypeId" v-if="false">
        <el-select
          v-model="queryParams.registerTypeId"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerTypeList"
            :key="index"
            :label="item.registerTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          style="width: 160px"
          placeholder="请选择招生年份"
          format="yyyy"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="box-container">
      <div class="custom-table">
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="info-row">
            <div class="col border" style="display: flex">
              <div style="margin-left: 15px; text-align: left; width: 100%">
                <div class="user-name">
                  <span
                    style="font-size: 18px; font-weight: bolder; color: #a52529"
                    >{{ row.userName }}</span
                  >
                </div>
                <div class="info">
                  <div class="flexinfo">
                    <div>进修科目：{{ row.registerDeptName }}</div>
                    <div
                      v-if="row.registerAllocationVoList.length > 0"
                      style="display: flex"
                    >
                      带教老师：
                      <div
                        v-for="(item, index) in row.registerAllocationVoList"
                        :key="index"
                        style="margin-right: 5px"
                      >
                        {{ item.teacherNickName }}
                      </div>
                    </div>

                    <div>
                      进修期限：{{ row.durationStartDate }} -
                      {{ row.durationEndDate }}
                    </div>
                    <div>
                      招生批次：{{
                        row.batchName || getDuration(row.durationStartDate)
                      }}
                    </div>
                    <div>申请单位：{{ row.unitHospitalName }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col border">
              <div class="desc">进修状态</div>
              <div class="systemColor">
                {{ row.cultureStatusName }}
              </div>
            </div>
            <div class="col border">
              <i
                class="el-icon-c-scale-to-original systemColor"
                style="font-size: 30px"
              ></i>
              <el-button
                size="mini"
                type="text"
                @click="detailOpen(row)"
                v-if="row.auditStatus == 3"
                >记录手册
              </el-button>
            </div>

            <div class="col border">
              <i
                class="el-icon-document-copy systemColor"
                style="font-size: 30px"
              ></i>
              <el-button
                size="mini"
                type="text"
                @click="revokeOpen(row)"
                v-if="row.auditStatus == 3"
                >结业申请
              </el-button>
            </div>
          </div>
          <div class="process-flow-row">
            <span v-if="row.beforeEndTime"
              >以下内容请在{{ row.beforeEndTime }}日以后填写</span
            >
            <ProcessFlow
              :process-data="row.workFlowList"
              @node-click="handleNodeClick($event, row)"
            />
          </div>
        </div>
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="告知书"
      :visible.sync="informShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div class="header-title">进修生告知书</div>
      <div style="line-height: 40px">
        (要求：请在报到后 一周内下载并打印
        <span
          class="download"
          @click="handleDownLoad('华山医院进修生告知书.pdf')"
          >华山医院进修生告知书<i class="el-icon-download"></i></span
        >，由本人签字后，上传PDF扫描原件)
      </div>
      <file-upload
        v-if="informForm"
        v-model="informForm.informUrl"
        :fileType="['pdf']"
        :limit="1"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="informSubmit">确 定</el-button>
        <el-button @click="informShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="承诺书"
      :visible.sync="promiseShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div class="header-title">行风自律承诺书</div>
      <div
        style="line-height: 40px"
        v-if="promiseForm && promiseForm.registerDeptId === 13"
      >
        (要求：请在报到后 一周内下载并打印
        <span
          class="download"
          @click="handleDownLoad('行风自律承诺书-护士.docx')"
          >行风自律承诺书-护士<i class="el-icon-download"></i></span
        >，由本人及相关负责人签字后，上传PDF扫描原件)
      </div>
      <div style="line-height: 40px" v-else>
        (要求：请在报到后 一周内下载并打印
        <span
          class="download"
          @click="handleDownLoad('行风自律承诺书-医生.docx')"
          >行风自律承诺书-医生<i class="el-icon-download"></i></span
        >，由本人及相关负责人签字后，上传PDF扫描原件)
      </div>
      <div style="line-height: 40px" v-if="false">
        (要求：请在报到后 一周内下载并打印
        <span
          class="download"
          @click="handleDownLoad('行风自律承诺书-管理.docx')"
          >行风自律承诺书-管理<i class="el-icon-download"></i></span
        >，由本人及相关负责人签字后，上传PDF扫描原件)
      </div>
      <file-upload
        v-if="promiseForm"
        v-model="promiseForm.promiseUrl"
        :fileType="['pdf']"
        :limit="1"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="promiseSubmit">确 定</el-button>
        <el-button @click="promiseShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="记录手册"
      :visible.sync="detailShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <registerManual
        v-if="detailShow"
        :index="index"
        :register-id="registerId"
        @close="handleClose"
      />
    </el-dialog>

    <el-dialog
      title="结业申请"
      :visible.sync="graduationShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerGraduation
        v-if="graduationShow"
        @openComment="openComment"
        :register-id="registerId"
        @openManual="detailShow = true"
        @close="handleClose"
      />
    </el-dialog>
    <el-dialog
      title="进修审核"
      :visible.sync="DialogVisible"
      width="350px"
      append-to-body
      center
      :close-on-click-modal="false"
    >
      <div
        style="
          text-align: center;
          margin-top: 20px;
          display: flex;
          justify-content: center;
        "
      >
        进修医院将在进修结束前完成审核，请耐心等待
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          @click="graduationShow = true"
          style="background-color: #7a7b7b; border-color: #1e98d7"
          >查看结业申请</el-button
        >
        <el-button
          @click="DialogVisible = false"
          style="color: #ffffff; background-color: #1e98d7"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="考勤"
      :visible.sync="attendanceShow"
      width="500px"
      append-to-body
      center
      :close-on-click-modal="false"
    >
      <div v-if="attendanceInfo">
        <div v-if="attendanceInfo.registerLeaveVoList.length == 0">
          当前考勤：正常
        </div>
        <div v-if="attendanceInfo.leaveStat">
          <div>
            <div>请假次数：{{ attendanceInfo.registerLeaveVoList.length }}</div>
            <div>请假天数：{{ attendanceInfo.leaveStat.leaveDays }}</div>
            <div>销假天数：{{ attendanceInfo.leaveStat.closeDays }}</div>
            <div style="display: flex; align-items: center">
              请假后进修时间：
              <span v-if="attendanceInfo.registerNoticeVo"
                >{{ attendanceInfo.registerNoticeVo.startDate }} -
                {{ attendanceInfo.registerNoticeVo.endDate }}</span
              >
              <div v-if="attendanceInfo.leaveStatusDesc" style="color: #a52529">
                （{{ attendanceInfo.leaveStatusDesc }}）
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="attendanceShow = false"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 短期证书弹窗（与 certificate 页面一致的展示和下载逻辑） -->
    <el-dialog
      title="短期证书"
      :visible.sync="certificateShow"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <img
        v-if="certificateShow"
        :src="
          baseURL + '/business/registerBase/queryByCertificate?id=' + registerId
        "
        style="width: 100%"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="certificateDownLoad"
          >下载短期证书</el-button
        >
        <el-button @click="certificateShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllRegisterDept } from "@/api/business/registerDept";
import {
  getRegisterInfo,
  indexListRegisterInfo,
  updateRegisterInfo,
} from "@/api/business/registerInfo";
import { setupBatchData } from "@/utils/batchUtils";

import { certificateDownLoadRegisterBase } from "@/api/business/registerBase";
import { listAllRegisterType } from "@/api/business/registerType";
import ProcessFlow from "@/views/business/registerBase/audit/components/ProcessFlow.vue";
import registerGraduation from "@/views/business/registerBase/audit/components/registerGraduation.vue";
import registerManual from "@/views/business/registerBase/audit/components/registerManual";

export default {
  components: { registerManual, registerGraduation, ProcessFlow },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      DialogVisible: false,
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      index: "1",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        noEndStudy:1,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: [],
      batchDateList: [],

      registerBaseVo: {},
      registerId: null,
      // 记录手册
      detailShow: false,
      // 结业申请
      graduationShow: false,
      // 告知书
      informShow: false,
      informForm: null,
      // 承诺书
      promiseShow: false,
      promiseForm: null,
      attendanceShow: false,
      attendanceInfo: null,
      // 短期证书
      certificateShow: false,
    };
  },
  async created() {
    await this.getbatch();
    this.getList();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    // 获取批次数据
    // 获取批次数据
    async getbatch() {
      await setupBatchData(this);
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    getList() {
      this.loading = true;
      indexListRegisterInfo(this.queryParams).then((response) => {
        this.dataList = response.rows;

        this.dataList.forEach((item) => {
          item.workFlowList.forEach((flowItem) => {
            if (flowItem.nodeName === "填写个人小结") {
              flowItem.canClick = true;
            }
            if (flowItem.nodeName === "带教老师打分") {
              flowItem.nodeName = "进修考评";
            }
            if (flowItem.nodeName === "进修医院确认考勤") {
              console.log("进修医院确认考勤");
              flowItem.nodeNameHtml = `进修医院<br/>确认考勤`;
            }
            flowItem.nodeStatusDesc = this.getDec(flowItem);
          });
          if (item.registerNoticeVo && item.registerNoticeVo.endDate) {
            let endDate = new Date(item.registerNoticeVo.endDate);
            endDate.setDate(endDate.getDate() - 14);
            item.beforeEndTime = `${endDate.getFullYear()}/${String(
              endDate.getMonth() + 1
            ).padStart(2, "0")}/${String(endDate.getDate()).padStart(2, "0")}`;
          }
        });
        this.total = response.total;
        this.loading = false;

        // 数据加载完成后刷新菜单权限，确保岗前培训菜单能够显示
        this.refreshMenuPermissions();
      });
    },
    // 刷新菜单权限
    refreshMenuPermissions() {
      // 重新获取路由权限，确保菜单显示正确
      this.$store
        .dispatch("GenerateRoutes")
        .then(() => {
          console.log("菜单权限已刷新");
        })
        .catch((err) => {
          console.error("刷新菜单权限失败:", err);
        });
    },
    getDec(value) {
      switch (value.nodeName) {
        case "填写个人小结":
          if (value.nodeStatus === 1) {
            return "已完成";
          } else {
            return "去填写";
          }
        case "填写临床工作表":
          if (value.nodeStatus === 1) {
            return "查看";
          } else {
            return "去填写";
          }
        case "进修考评":
          if (value.nodeStatus === 1) {
            return "查看考核";
          } else {
            return "待考核";
          }

        case "完成进修评价":
          if (value.nodeStatus === 1) {
            return "查看评价";
          } else {
            return "待评价";
          }
        case "进修医院确认考勤":
          return "查看考勤";

        case "结业申请":
          return value.nodeStatusDesc;
      }
    },
    openComment(index) {
      this.detailShow = true;
      this.index = index;
    },
    handleClose() {
      this.getList();
      this.detailShow = false;
      this.graduationShow = false;
      this.informShow = false;
      this.promiseShow = false;
      this.attendanceShow = false;
      this.certificateShow = false;
    },
    // 告知书
    informOpen(row) {
      this.informForm = row;
      this.informShow = true;
    },
    informSubmit() {
      if (!this.informForm.informUrl) {
        this.$message.error("请上传文件");
        return;
      }
      updateRegisterInfo(this.informForm).then((response) => {
        this.$modal.msgSuccess("上传成功");
        this.informShow = false;
      });
    },
    //根据期限获取批次
    getDuration(value) {
      if (value) {
        return parseInt(value.split("/")[0], 10);
      }
    },

    openAttendanceDialog(row) {
      getRegisterInfo(row.id).then((response) => {
        this.attendanceInfo = response.data;
        this.attendanceShow = true;
      });
    },
    handleNodeClick(event, row) {
      console.log(event);
      if (!event.canClick) {
        return;
      }
      switch (event.nodeName) {
        case "填写临床工作表":
          this.index = "2";
          this.registerId = row.id;
          this.detailShow = true;

          break;
        case "填写个人小结":
          this.index = "4";
          this.registerId = row.id;
          this.detailShow = true;

          break;
        case "完成进修评价":
          this.index = "5";
          this.registerId = row.id;
          this.detailShow = true;
          break;
        case "进修医院确认考勤":
          this.openAttendanceDialog(row);
          break;
        case "进修考评":
          this.index = "3";
          this.registerId = row.id;
          this.detailShow = true;

          break;
        case "结业申请":
          if (event.nodeStatus == 0 && event.nodeStatusDesc == "待审核") {
            this.registerId = row.id;
            this.DialogVisible = true;
          } else {
            if (event.nodeStatusDesc == "已结业") {
              let durationDays = null;
              if (
                row.registerNoticeVo &&
                row.registerNoticeVo.startDate &&
                row.registerNoticeVo.endDate
              ) {
                const start = new Date(row.registerNoticeVo.startDate);
                const end = new Date(row.registerNoticeVo.endDate);
                if (!isNaN(start) && !isNaN(end)) {
                  durationDays = Math.floor(
                    (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
                  );
                }
              }
              if (durationDays !== null && durationDays < 30) {
                this.$confirm("您的进修已结业，点击下载电子证书", "提示", {
                  confirmButtonText: "下载",
                  cancelButtonText: "取消",
                  type: "success",
                })
                  .then(() => {
                    this.registerId = row.id;
                    this.certificateShow = true;
                  })
                  .catch(() => {});
                return;
              } else {
                this.$alert("结业手续办理时间及地点，请关注科室通知", "提示", {
                  confirmButtonText: "确定",
                  type: "success",
                  callback: (action) => {},
                });
                return;
              }
            } else {
              this.registerId = row.id;
              this.graduationShow = true;
            }
          }
          break;
        default:
          break;
      }
    },
    // 承诺书
    promiseOpen(row) {
      this.promiseForm = row;
      this.promiseShow = true;
    },
    promiseSubmit() {
      if (!this.promiseForm.promiseUrl) {
        this.$message.error("请上传文件");
        return;
      }
      updateRegisterInfo(this.promiseForm).then((response) => {
        this.$modal.msgSuccess("上传成功");
        this.promiseShow = false;
      });
    },
    handleDownLoad(fileName) {
      window.open(this.baseURL + "/profile/template/" + fileName);
    },
    // 记录手册
    detailOpen(row) {
      this.registerId = row.id;
      this.detailShow = true;
    },
    // 结业申请
    revokeOpen(row) {
      this.registerId = row.id;
      this.graduationShow = true;
    },
    // 短期证书下载
    certificateDownLoad() {
      certificateDownLoadRegisterBase({ id: this.registerId }).then(
        (response) => {
          let b = new Blob([response]);
          let url = window.URL.createObjectURL(b);
          let a = document.createElement("a");
          a.href = url;
          a.download = "短期培训证明.jpg";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

.header-title {
  background-color: #f2f3f5;
  height: 50px;
  line-height: 50px;
  font-weight: bolder;
  font-size: 18px;
  padding-left: 15px;
  border-left: 6px solid #a52529;
  border-radius: 5px;
  margin-bottom: 15px;
}
/* 新增：流程图行的样式 */
.process-flow-row {
  width: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.download {
  color: #409eff;
  text-decoration: underline;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .desc {
      font-size: 12px;
      color: #999;
      margin-top: 10px;
      font-weight: normal;
    }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register {
    display: flex;
    flex-direction: column;
    /* 改为垂直布局 */
    border: 1px solid rgb(232, 232, 232);
    font-size: 14px;
    margin-bottom: 10px;
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 150px;
    }
    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;
      font-size: 14px;
      margin-top: 10px;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;
        width: 450px;
        line-height: 20px;
        flex: 1;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 400px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 140px;
    }

    .col:nth-child(3) {
      width: 140px;
    }

    .col:nth-child(4) {
      width: 140px;
    }

    .col:nth-child(5) {
      width: 140px;
    }
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
}
</style>
